package com.topisv.tms.web.phone;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.stock.instorage.InstorageCountItem;
import com.topisv.tms.entity.stock.instorage.InstorageCountTask;
import com.topisv.tms.entity.stock.instorage.InstorageUpSubTaskItem;
import com.topisv.tms.entity.stock.instorage.InstorageUpTask;
import com.topisv.tms.entity.stock.instorage.InstorageUpTaskItem;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillItemPre;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.repository.stock.instorage.InstorageCountItemDao;
import com.topisv.tms.repository.stock.instorage.InstorageCountTaskDao;
import com.topisv.tms.service.stock.instorage.InstorageCountTaskService;
import com.topisv.tms.service.stock.instorage.InstorageUpDispatchTaskService;
import com.topisv.tms.service.stock.instorage.InstorageUpTaskService;
import com.topisv.tms.service.work.WorkTaskService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/phone")
public class WMSInstorageController {
	
	private static final Logger log = LoggerFactory.getLogger(WMSInstorageController.class);
	
	@Autowired
	private InstorageCountTaskService instorageCountTaskService;
	@Autowired
	private InstorageCountTaskDao instorageCountTaskDao;
	@Autowired
    private InstorageCountItemDao instorageCountItemDao;
	@Autowired
	private InstorageUpTaskService instorageUpTaskService;
	@Autowired
	private InstorageUpDispatchTaskService instorageUpDispatchTaskService;
	@Autowired
    private WorkTaskService workTaskService;
   //////////////////////////////////////////////////////////点收接口///////////////////////////////////////////////////////////////////////
	
	/**
	 * 查询点收任务列表
	 * @param jobuuid 用户UUID
	 * @param response
	 */
	@RequestMapping(value = "ajaxCountTaskList")
	public void ajaxCountTaskList(@RequestParam(value = "jobuuid") String jobuuid,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
//			User curUser=this.accountService.findUserByJobuuid(jobuuid);
			List<InstorageCountTask> taskList = new ArrayList<InstorageCountTask>();
			
			//我的任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", jobuuid);
		    param_my.put("status", "myTask"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
		    List<InstorageCountTask> myTaskList=this.instorageCountTaskService.loadTaskByParam(param_my);
		    taskList.addAll(myTaskList);
		    
		    //如果是派友用户,初始化数据
//			if("paiu".equals(curUser.getUserType())){
//				//未分配的拣货任务
//			    Map<String, Object> param=new HashMap<String, Object>();
//			    param.put("customerCodes", StringUtils.isBlank(curUser.getCustomers())?"blank":curUser.getCustomers());
//			    param.put("areagroups", StringUtils.isBlank(curUser.getAreagroups())?"blank":curUser.getAreagroups());
//			    param.put("status", "undo"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
//			    List<InstorageCountTask> untakedTaskList=this.instorageCountTaskService.loadTaskByParam(param);
//			    taskList.addAll(untakedTaskList);
//			}
//		    
//		    //如果是商家用户,初始化数据
//			if("customer".equals(curUser.getUserType())){
//				//未分配的拣货任务
//				String customerCode=curUser.getCustomerCode();
//			    Map<String, Object> param=new HashMap<String, Object>();
//			    param.put("customerCodes", StringUtils.isBlank(customerCode)?"blank":customerCode);
//			    param.put("areagroups", StringUtils.isBlank(curUser.getAreagroups())?"blank":curUser.getAreagroups());
//			    param.put("status", "undo"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
//			    List<InstorageCountTask> untakedTaskList=this.instorageCountTaskService.loadTaskByParam(param);
//			    taskList.addAll(untakedTaskList);
//			}
		    for(InstorageCountTask t:taskList){
				if("6".equals(t.getBill().getStatus())){
					t.setStatus("cancel");
				}
			}
			 //取消单的排后面
		    Collections.sort(taskList, new Comparator<InstorageCountTask>() {
	            public int compare(InstorageCountTask arg0, InstorageCountTask arg1) {
	                return arg1.getStatus().compareTo(arg0.getStatus());
	            }
	        });
		    json.put("status", "1"); //查询成功
			json.put("content", taskList); //任务列表
			
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	/**
	 * 未领取点收的任务
	 * @param jobuuid 
	 * @param customerCode  商家编码
	 * @param warehouseCode 仓库编码
	 * @param response
	 */
	@RequestMapping(value = "ajaxUnCountTaskList")
	public void ajaxUnCountTaskList(
			@RequestParam(value = "jobuuid",required=false) String jobuuid,
			@RequestParam(value = "customerCodes",required=false) String customerCodes,
			@RequestParam(value = "warehouseCodes",required=false) String warehouseCodes,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			//未分配的上架任务
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("customerCodes", StringUtils.isBlank(customerCodes)?"blank":customerCodes);
		    param.put("areagroups", StringUtils.isBlank(warehouseCodes)?"blank":warehouseCodes);
		    param.put("status", "undo");
		    List<InstorageCountTask> taskList=this.instorageCountTaskService.loadTaskByParam(param);
		    List<InstorageCountTask> untakedTaskList = new ArrayList<InstorageCountTask>();
			for(InstorageCountTask t:taskList){
				if(!"6".equals(t.getBill().getStatus())){
					untakedTaskList.add(t);
				}
			}
			json.put("status", "1");
			json.put("untakedTaskList", untakedTaskList);
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	
	}
	/**
	 * 领取点收任务
	 * @param jobuuid
	 * @param taskId 任务ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxTakeCountTask")
	public void ajaxTakeCountTask(@RequestParam(value = "jobuuid") String jobuuid,@RequestParam(value = "taskId") String taskId,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			//领取任务
			String msg=this.instorageCountTaskService.takeTask(Long.parseLong(taskId),jobuuid);
			if("success".equals(msg)){
				json.put("status", "1"); //领取任务成功
			}else if("token".equals(msg)){
				json.put("status", "2"); //任务已被领取
			}else{
				json.put("status", "0");
			}
			
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * 点收新流程
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxCountNew")
	public void ajaxCountNew(
			@RequestParam(value = "errorFlag",required=false) String errorFlag,
			@RequestParam(value = "billCode") String billCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "num") String num,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("PDA.ajaxCountNew", taskCode, "-");
            if (!isLockSuccess) {
                json.put("status", "0");
                json.put("content", "当前任务已在处理中，请勿重复处理！");
                return;
            }
            
			String content = instorageCountTaskService.findSkuExist(billCode, sku, customerCode);
			if(content != null){
				json.put("status","0");
				json.put("content",content);
			}else {
				Integer skuNum = Integer.parseInt(num);
				resultMap = this.instorageCountTaskService.countNew(taskCode, sku, skuNum, errorFlag);
				String msg = (String)resultMap.get("msg");
				if("success".equals(msg)){
					List<InstorageCountItem> items=this.instorageCountTaskService.findByTaskCode(taskCode);
					List<InstorageBillItemPre> preItems = (List<InstorageBillItemPre>)resultMap.get("preitems");
					if(null != preItems ){
						Map<String,Integer> countMap = new HashMap<String,Integer>();
						for(InstorageBillItemPre itemPre : preItems){
							countMap.put(itemPre.getSkuCode(), itemPre.getGoodsNum());
						}
						for(InstorageCountItem cItem : items){
							cItem.setPlanNum(countMap.get(cItem.getSku()));
						}
					}
					json.put("status", "1");
					json.put("items", items);
					json.put("content", msg);
				}else if("NoConfigure".equals(msg)){
					json.put("status", "1");
					json.put("content", msg);
				}else {
					json.put("content", msg);
					json.put("status", "0");
				}
			}
		} catch (PaiUException e) {
			json.put("status", e.getErrorCode());
			json.put("content", e.getMessage());
		}catch (Exception ex){
			log.error("error",ex);
			json.put("status", "0");
			json.put("content", "服务器异常");
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("PDA.ajaxCountNew", taskCode);
            }
            out.print(json.toString());
            log.debug("点收结果：{}", json.toString());
        }
	}
	
	/**
	 * 点收明细列表
	 * @param uptaskCode 任务编号
	 * @param sku  SKU
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxCountDetail")
	public void ajaxCountDetail(
			@RequestParam(value = "billCode") String billCode,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			List<InstorageCountItem> items=this.instorageCountTaskService.findByBillCode(billCode);
			List<InstorageBillItemPre> preItems= this.instorageCountTaskService.loadBillItemPres(billCode);
	
    		if(null != preItems ){
				Map<String,Integer> countMap = new HashMap<String,Integer>();
				
				for(InstorageBillItemPre itemPre : preItems){
					countMap.put(itemPre.getSkuCode(), itemPre.getGoodsNum());
				}
				for(InstorageCountItem cItem : items){
					cItem.setPlanNum(countMap.get(cItem.getSku()));
				}
			}        		
			json.put("status", "1");
			json.put("items", items);
			json.put("content", "查询成功");
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	/**
	 * 删除点收明细项
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCountItemDel")
	@ResponseBody
	public void ajaxDeleteCountItem(@RequestParam(value = "itemId") String itemId,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			InstorageCountItem item = this.instorageCountItemDao.findOne(Long.valueOf(itemId));
			
			if(item == null || item.getTaskCode() == null){
	            json.put("status", "0");
	            json.put("content", "删除失败"); 
			}else{
	            InstorageCountTask task=instorageCountTaskDao.loadByTaskCode(item.getTaskCode());
	            if("finish".equals(task.getStatus())){
	                json.put("status", "0");
	                json.put("content", "删除失败，改任务已点收完成，请检查！");  
	            }else {
	                String result = this.instorageCountTaskService.deleteCountItem(Long.parseLong(itemId));
	                if ("success".equals(result)) {
	                    json.put("status", "1");
	                    json.put("content", "删除成功");
                    }else {
                        json.put("status", "0");
                        json.put("content", "删除失败。任务已完成或不是点收中状态");
                    }
	            }
			}
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "删除失败");
		}
		out.print(json.toString());
	}
	/**
	 * 整箱点收
	 * @param taskCode 任务编号
	 * @param sku  SKU
	 * @param num 数量/箱
	 * @param boxCode 箱编码
	 * @param response
	 */
	@RequestMapping(value = "ajaxBoxCount")
	public void ajaxBoxCount(
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "num") Integer num,
			@RequestParam(value = "boxCode") String boxCode,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			//整箱点收
			String msg=this.instorageCountTaskService.count_box(taskCode,sku,num,boxCode);
			if("success".equals(msg)){
				json.put("status", "1"); //点收成功
			}else{
				json.put("status", "0"); //点收失败
			}
			
			//整箱列表
			List<InstorageCountItem> itemList_box=this.instorageCountTaskService.loadByTaskCode(taskCode,"box");
			json.put("itemList_box", itemList_box);
			//散货列表
			List<InstorageCountItem> itemList_single=this.instorageCountTaskService.loadByTaskCode(taskCode,"single");
			json.put("itemList_single", itemList_single);
			
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * 散货点收
	 * @param taskCode 任务编号
	 * @param sku  SKU	
	 * @param response
	 */
	@RequestMapping(value = "ajaxSingleCount")
	public void ajaxSingleCount(
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "sku") String sku,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			//散货点收
			String msg=this.instorageCountTaskService.count_single(taskCode,sku);
			if("success".equals(msg)){
				json.put("status", "1"); //点收成功
			}else{
				json.put("status", "0"); //点收失败
			}
			
			//整箱列表
			List<InstorageCountItem> itemList_box=this.instorageCountTaskService.loadByTaskCode(taskCode,"box");
			json.put("itemList_box", itemList_box);
			//散货列表
			List<InstorageCountItem> itemList_single=this.instorageCountTaskService.loadByTaskCode(taskCode,"single");
			json.put("itemList_single", itemList_single);
			
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * 点收完成
	 * @param taskCode 任务编号
	 * @param response
	 */
	@RequestMapping(value = "ajaxCompleteCount")
	public void ajaxCompleteCount(@RequestParam(value = "taskCode") String taskCode, HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("ajaxCompleteCount", taskCode, "-");
            if (!isLockSuccess) {
                json.put("status", "0");
                json.put("content", "当前任务已在处理中，请勿重复处理！");
                out.print(json.toString());
                return;
            }
			
			//完成点收
			String msg=this.instorageCountTaskService.finishCountNew(taskCode);
			if("success".equals(msg)){
				json.put("status", "1"); //成功
			}else{
				json.put("status", "0"); //失败
			}
			
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0"); //服务器异常
			if (e instanceof PaiUException) {
				json.put("content", ((PaiUException) e).getMessage());
			} else {
				json.put("content", "服务器异常");
			}
		} finally {
		    if (isLockSuccess) {
                workTaskService.releaseLock("ajaxCompleteCount", taskCode);
            }
		}
		
		out.print(json.toString());
	}
	
   
	
	/**
	 * 领取上架任务
	 * @param jobuuid
	 * @param taskId  任务ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxTakeUpTask")
	public void ajaxTakeUpTask(@RequestParam(value = "jobuuid") String jobuuid,@RequestParam(value = "taskId") Long taskId,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			//领取任务
			String msg=this.instorageUpTaskService.takeTask(taskId,jobuuid);
			if("success".equals(msg)){
				json.put("status", "1"); //领取任务成功
				json.put("content", "任务成功");
			}else if("token".equals(msg)){
				json.put("status", "2"); //任务已被领取
				json.put("content", "任务已被领取");
			}else{
				json.put("status", "0");
				json.put("content", "领用失败");
			}
			
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * 整箱上架
	 * @param uptaskCode 任务编号
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxUpBox")
	public void ajaxUpBox(
			@RequestParam(value = "uptaskCode") String uptaskCode,
			@RequestParam(value = "stockCode") String stockCode,
			@RequestParam(value = "boxCode") String boxCode,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			json.put("status", "0");
			json.put("content", "移动端暂时关闭该功能");
			/*
			 *  手机上架暂时关闭
			 * //整箱上架
			String msg=this.instorageUpTaskService.up_box(uptaskCode,boxCode,stockCode);
			if("continue".equals(msg)){
				json.put("status", "1"); //上架成功，继续
			}else if("finishing".equals(msg)){
				json.put("status", "2"); //上架成功，此任务完成
			}else{
				json.put("status", "0"); //上架失败
			}*/
			
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	 //////////////////////////////////////////////////////////上架接口///////////////////////////////////////////////////////////////////////
		/**
		 *  查询上架任务列表
		 * @param jobuuid
		 * @param response
		 */
		@RequestMapping(value = "ajaxUpTaskList")
		public void ajaxUpTaskList(@RequestParam(value = "jobuuid") String jobuuid,HttpServletResponse response) {

			JSONObject json = null;
			PrintWriter out = null;
			try {
				json = new JSONObject();
				out = response.getWriter();
				
//				User curUser=this.accountService.findUserByJobuuid(jobuuid);
				List<InstorageUpTask> taskList = new ArrayList<InstorageUpTask>();
				
				//我的任务
				Map<String, Object> param_my=new HashMap<String, Object>();
			    param_my.put("workerUuid", jobuuid);
			    param_my.put("status", "myTask"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
			    List<InstorageUpTask> TaskList=this.instorageUpTaskService.loadTaskByParam(param_my);
			    //update LiBin 20161017 bug563 为取消单的任务 增加标示
			    for(InstorageUpTask t:TaskList){
                    if("6".equals(t.getBill().getStatus())){
                        t.setStatus("cancel");
                    }
                    if ("returnOrder".equals(t.getBill().getBillType()) ) {//&& "退回单完好件入库".equals(t.getBill().getRemarks())
                        t.setTaskFromType("returnOrder");
                    }
                }
			    taskList.addAll(TaskList);
			    //update LiBin 20161017 bug563 放在这 不起作用 移上去
//			    for(InstorageUpTask t:TaskList){
//					if("6".equals(t.getBill().getStatus())){
//						t.setStatus("cancel");
//					}
//				}
				
			    //取消单的排后面
			    Collections.sort(taskList, new Comparator<InstorageUpTask>() {
		            public int compare(InstorageUpTask arg0, InstorageUpTask arg1) {
		                return arg1.getStatus().compareTo(arg0.getStatus());
		            }
		        });
			    //派友用户
//				if("paiu".equals(curUser.getUserType())){
//					//未分配的任务
//				    Map<String, Object> param=new HashMap<String, Object>();
//				    param.put("customerCodes", StringUtils.isBlank(curUser.getCustomers())?"blank":curUser.getCustomers());
//				    param.put("areagroups", StringUtils.isBlank(curUser.getAreagroups())?"blank":curUser.getAreagroups());
//				    param.put("status", "undo"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
//				    List<InstorageUpTask> untakedTaskList=this.instorageUpTaskService.loadTaskByParam(param);
//				    taskList.addAll(untakedTaskList);
//				}
			    
			    //商家用户
//				if("customer".equals(curUser.getUserType())){
//					//未分配的任务
//					String customerCode=curUser.getCustomerCode();
//				    Map<String, Object> param=new HashMap<String, Object>();
//				    param.put("customerCodes", StringUtils.isBlank(customerCode)?"blank":customerCode);
//				    param.put("areagroups", StringUtils.isBlank(curUser.getAreagroups())?"blank":curUser.getAreagroups());
//				    param.put("status", "undo"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
//				    List<InstorageUpTask> untakedTaskList=this.instorageUpTaskService.loadTaskByParam(param);
//				    taskList.addAll(untakedTaskList);
//				}
				
			    json.put("status", "1"); //查询成功
				json.put("content", taskList); //任务列表
				
			} catch (Exception e) {
				
				log.error("error",e);
				json.put("status", "0");
				json.put("content", "服务器异常");
			}
			out.print(json.toString());
		}
		
		
		/**
		 * 散货上架领取任务查询
		 * @param jobuuid 
		 * @param customerCode  商家编码
		 * @param warehouseCode 仓库编码
		 * @param response
		 */
		@RequestMapping(value = "ajaxUpSingleReceiveList")
		public void ajaxUpSingleReceiveList(
				@RequestParam(value = "jobuuid",required=false) String jobuuid,
				@RequestParam(value = "customerCodes",required=false) String customerCodes,
				@RequestParam(value = "warehouseCodes",required=false) String warehouseCodes,
				HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
			try {
				json = new JSONObject();
				out = response.getWriter();
				
				//未分配的上架任务
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", StringUtils.isBlank(customerCodes)?"blank":customerCodes);
			    param.put("areagroups", StringUtils.isBlank(warehouseCodes)?"blank":warehouseCodes);
			    param.put("status", "undo"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
			    List<InstorageUpTask> TaskList=this.instorageUpTaskService.loadTaskByParam(param);
			  
			    //update LiBin 20161017 bug563 修改标记状态
			    List<InstorageUpTask> untakedTaskList = new ArrayList<InstorageUpTask>();
				for(InstorageUpTask t:TaskList){
					if(!"6".equals(t.getBill().getStatus())){
						if ("returnOrder".equals(t.getBill().getBillType()) ) {//&& "退回单完好件入库".equals(t.getBill().getRemarks())
						    t.setTaskFromType("returnOrder");
						}
						untakedTaskList.add(t);
					}
				}
				json.put("status", "1");
				json.put("untakedTaskList", untakedTaskList);
			} catch (Exception e) {
				log.error("error",e);
				json.put("status", "0");
				json.put("content", "服务器异常");
			}
			out.print(json.toString());
		
		}
	/**
	 * 散货上架
	 * @param uptaskCode 任务编号
	 * @param sku  SKU
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxUpSingle")
	public void ajaxUpSingle(
			@RequestParam(value = "errorFlag",required=false) String errorFlag,
			@RequestParam(value = "uptaskCode") String uptaskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "skuNum") String skuNum,
			@RequestParam(value = "stockCode") String stockCode,
			@RequestParam(value = "boxCode") String boxCode,
		HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			isLockSuccess = workTaskService.lock("ajaxUpSingle", uptaskCode + sku + stockCode + boxCode + errorFlag, "-");
            if (!isLockSuccess) {
                json.put("status", "0");
                json.put("content", "当前任务已在处理中，请勿重复处理！");
                out.print(json.toString());
                return;
            }
			InstorageUpTaskItem taskItem = new InstorageUpTaskItem();
			taskItem.setErrorFlag(errorFlag);
			taskItem.setSkuCode(sku);
			taskItem.setUpTaskCode(uptaskCode);
			taskItem.setNum(StringUtils.isEmpty(skuNum)?0:Integer.valueOf(skuNum));
			taskItem.setStockCode(stockCode);
			taskItem.setBoxCode(boxCode);
			instorageUpTaskService.upNew(taskItem);
			
			List<InstorageUpSubTaskItem> unUpItem = instorageUpDispatchTaskService.unUpDispatchItem(uptaskCode);
			json.put("status", "1");
			json.put("unUpItem", unUpItem);
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			if (e instanceof PaiUException) {
                 json.put("content", e.getMessage());
            }else {
                json.put("content", "服务器异常");
            }
		}finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("ajaxUpSingle", uptaskCode + sku + stockCode + boxCode + errorFlag);
            }
        }
		out.print(json.toString());
	}
	/**
	 * 散货上架明细列表
	 * @param uptaskCode 任务编号
	 * @param sku  SKU
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxUpSingleDetail")
	public void ajaxUpSingleDetail(
			@RequestParam(value = "uptaskCode") String uptaskCode,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			List<InstorageUpTaskItem> itemList = this.instorageUpTaskService.findByTaskCode(uptaskCode);
			List<InstorageUpSubTaskItem> unUpItem = instorageUpDispatchTaskService.unUpDispatchItem(uptaskCode);
			json.put("status", "1");
			json.put("itemList", itemList);
			json.put("unUpItem", unUpItem);
			json.put("content", "查询成功");
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	/**
	 * 散货上架删除
	 * @param uptaskCode 任务编号
	 * @param sku  SKU
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxUpSingleDel")
	public void ajaxUpSingleDel(
			@RequestParam(value = "uptaskCode") String uptaskCode,
			@RequestParam(value = "uptaskItemId") String uptaskItemId,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			instorageUpTaskService.deleteItem(Long.valueOf(uptaskItemId));
			
			json.put("status", "1");
			json.put("content", "删除成功");
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * 散货上架完成
	 * @param uptaskCode 任务编号
	 * @param sku  SKU
	 * @param stockCode 库位号
	 * @param boxCode 箱位号
	 * @param response
	 */
	@RequestMapping(value = "ajaxUpSingleFinish")
	public void ajaxUpSingleFinish(
			@RequestParam(value = "uptaskCode") String uptaskCode,
		HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			instorageUpTaskService.finishUpTask(uptaskCode);
			json.put("status", "1");
			json.put("content", "上架任务完成");
			
		} catch (Exception e) {
			
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * 新老上架流程推荐库位方法
	 * 规则:推荐逻辑是查找SKU在哪些库位上有库存，将所有库存查出后，取库存数量最少的那个库位。如果没找到，推荐库位显示“-”
	 * @param customerCode
	 * @param warehouseCode
	 * @param sku
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "recommendStock")
	public void recommendStock(
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "sku") String sku,
			HttpServletResponse response){
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			List<Object> list=instorageUpTaskService.recommendStock(customerCode,warehouseCode,sku);
			if(list != null && !list.isEmpty()){
				json.put("recommendStock",list.get(0));
			}else{
				json.put("recommendStock","-");
			}
			json.put("status", "1");
			json.put("content", "成功");
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
}

  

    
